﻿#if NETSTANDARD2_0 || NETCOREAPP3_0
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Concurrent;

namespace Longbow.Configuration
{
    /// <summary>
    /// 配置项操作扩展类
    /// </summary>
    public static class ConfigurationManager
    {
        private static readonly ConcurrentDictionary<string, object> optionsPool = new ConcurrentDictionary<string, object>();
        private static Lazy<IConfiguration> _lazy;

        /// <summary>
        /// 获得 当前应用 IConfiguration 实例
        /// </summary>
        public static IConfiguration AppSettings { get { return _lazy.Value; } }

        /// <summary>
        /// 通过指定 Section 名称 获得强类型值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">配置项键值</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static T GetValue<T>(string key, T defaultValue) => AppSettings.GetValue(key, defaultValue);

        /// <summary>
        /// 通过指定 Section 名称 获得配置项类实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueFactory">默认值</param>
        /// <returns></returns>
        public static T Get<T>(Func<T> valueFactory = null)
        {
            var section = AppSettings.GetSection<T>();
            T ret = default;
            if (section.Exists()) ret = section.Get<T>();
            if (ret == default && valueFactory != null) ret = valueFactory.Invoke();
            return ret;
        }

        /// <summary>
        /// 通过指定 Section 名称 获取子节点配置项 IConfigurationSection 实例
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IConfiguration GetSection(string key) => AppSettings.GetSection(key);

        /// <summary>
        /// 通过指定 Section 名称 获取子节点配置项 IConfigurationSection 实例
        /// </summary>
        /// <returns></returns>
        public static IConfiguration GetSection<T>() => AppSettings.GetSection<T>();

        /// <summary>
        /// Services 注入时调用
        /// </summary>
        /// <param name="services"></param>
        internal static void RegisterConfigurationManager(this IServiceCollection services)
        {
            _lazy = new Lazy<IConfiguration>(() =>
            {
                return services.BuildServiceProvider().GetRequiredService<IConfiguration>();
            });
        }
    }
}
#endif
